package com.kitty.web.client.service;

import com.alibaba.druid.util.Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.kitty.common.cache.entity.AppProperties;
import com.kitty.common.thread.IdGenerator;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.config.Server;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.map.service.MapService;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBox;
import com.kitty.game.player.model.PlayerProfile;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.utils.JsonUtils;
import com.kitty.game.utils.RandomName;
import com.kitty.game.utils.StringUtil;
import com.kitty.mina.cache.DataCache;
import com.kitty.web.client.AiInfo;
import com.kitty.web.client.common.RoleTemp;
import com.kitty.web.common.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.nutz.castor.castor.String2Object;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class AiService {
    @Autowired
    Dao dao;
    @Autowired
    MapService mapService;
    public void joinAi(AiInfo aiInfo){
        String stringKey = aiInfo.getStringKey();
        String joinTeamKey = DataCache.REDIS_DATA.get("joinTeamKey");
        List<AppProperties> key_ = dao.query(AppProperties.class, Cnd.where("key_", "=", "joinTeamKey"));
        if(key_.size() == 0){
            AppProperties appProperties = new AppProperties();
            appProperties.setKey_("joinTeamKey");
            appProperties.setValue_(stringKey);
            appProperties.setType_("关键字进组");
            appProperties.setClasstype("zaxiang");
            dao.insert(appProperties);
        }else{
            key_.get(0).setValue_(stringKey);
            dao.insertOrUpdate(key_);
        }
        DataCache.REDIS_DATA.put("joinTeamKey",stringKey);
    }



    public void createAi(AiInfo aiInfo){
        Server server = SpringUtils.getBean(ServerService.class).getServer();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ai.txt");
        RoleTemp temp = JSONObject.parseObject(Utils.read(inputStream), RoleTemp.class);
        log.info("获取AI假人模板。");
        int num = aiInfo.getAiNum();
        int level = aiInfo.getLevel();
        if(level == 0){
            log.info("开始生成新手任务AI。");
            //新手假人
            String lv_00 = temp.getLv_00().get("default");
            Role roleTemp = JSON.toJavaObject(JSONObject.parseObject(lv_00), Role.class);
            for (int i = 0; i < num; i++) {
                //随机相性
                int polar = ThreadLocalRandom.current().nextInt(5)+1;
                //随机性别
                int gender = ThreadLocalRandom.current().nextInt(2)+1;
                Role role = new Role();
                BeanUtils.copyProperties(roleTemp,role);
                String name  = RandomName.getChineseName();
                role.setName(RandomName.getChineseName());
                role.setRoleId(getRoleId());
                role.setSid("ww"+getRandomString());
                role.setUid(IdGenerator.getNextId());
                role.setAitype(2);
                role.setPolar((short)polar);
                role.setGender((byte) gender);
                role.setRoleIcon(mapService.heroIcon(role.getGender(), role.getPolar()));
                role.setDistName(server.getName());
                SpringUtils.getPlayerService().saveToCache(role);
                role.aiSave();
                log.info("生成AI：{},门派：{}，性别：{}",name,polar,gender);
                SpringUtils.getPlayerService().addPlayerProfile(new PlayerProfile(role));
            }
        }else{

            //战斗假人
            Map<String, String> roleByLevel = getRoleByLevel(temp, level);
            for (int i = 0; i < num; i++) {
                int newLevel = level;
                //随机相性
                int polar = ThreadLocalRandom.current().nextInt(5)+1;
                String lv_role = roleByLevel.get(polar + "");
                Role roleTemp = JSON.toJavaObject(JSONObject.parseObject(lv_role), Role.class);
                Role role = new Role();
                BeanUtils.copyProperties(roleTemp,role);
                String name  = RandomName.getChineseName();
                role.setName(RandomName.getChineseName());
                role.setRoleId(getRoleId());
                role.setSid("ww"+getRandomString());
                role.setUid(IdGenerator.getNextId());
                role.setAitype(1);
                role.setDistName(server.getName());
                String petBoxJson = role.getPetBoxJson();
                if(StringUtils.isNotEmpty(petBoxJson)){
                    PetBox petBox =JsonUtils.string2Object(petBoxJson,PetBox.class);
                    Map<Integer, Pet> allPets = petBox.getAllPets();
                    for (Map.Entry<Integer, Pet> integerPetEntry : allPets.entrySet()) {
                        Pet value = integerPetEntry.getValue();
                        value.setHostId(role.getRoleId());
                    }
                    String s = JsonUtils.object2String(petBox);
                    role.setPetBoxJson(s);
                }
                SpringUtils.getPlayerService().saveToCache(role);
                PetBox petBox = role.getPetBox();
                Map<Integer, Pet> allPets = petBox.getAllPets();
                for (Map.Entry<Integer, Pet> integerPetEntry : allPets.entrySet()) {
                    int petId = SpringUtils.getIdentityService().getNextId(IdentityType.ROLE);
                    Pet value = integerPetEntry.getValue();
                    int oldId = value.getId();
                    value.setHostId(role.getRoleId());
                    value.setId(petId);
                    //修改参战宠物ID
                    if(oldId == petBox.getFightPetId()){
                        petBox.setFightPetId(petId);
                        petBox.setFightYangPetId(petId);
                    }
                    //修改坐骑宠物ID
                    if(oldId == role.getMount()){
                        role.setMount(petId);
                    }
                }
                role.setPetBox(petBox);
                newLevel = newLevel+ThreadLocalRandom.current().nextInt(9);
                role.setLevel((short)newLevel);
                role.aiSave();
                log.info("生成AI：{},门派：{}，等级：{},生成等级：{}",name,polar,level,newLevel);
                SpringUtils.getPlayerService().addPlayerProfile(new PlayerProfile(role));
            }

        }

    }
    public Map<String,String> getRoleByLevel(RoleTemp roleTemp,int level){
        Map<String,String> temp = new HashMap<>();
        if (level == 60) {
            temp = roleTemp.getLv_60();
        }else if (level == 70) {
            temp = roleTemp.getLv_70();
        } else if (level == 80) {
            temp = roleTemp.getLv_80();
        } else if (level == 90) {
            temp = roleTemp.getLv_90();
        } else if (level == 100) {
            temp = roleTemp.getLv_100();
        } else if (level == 110) {
            temp = roleTemp.getLv_110();
        } else if (level == 120) {
            temp = roleTemp.getLv_120();
        }else if (level == 130) {
            temp = roleTemp.getLv_130();
        }else if (level == 140) {
            temp = roleTemp.getLv_140();
        }else if (level == 150) {
            temp = roleTemp.getLv_150();
        }else if (level == 160) {
            temp = roleTemp.getLv_160();
        }else if (level == 170) {
            temp = roleTemp.getLv_170();
        }
        return temp;
    }
    public static void main(String[] args) {
        for (int i = 0; i < 9999; i++) {
            int polar = ThreadLocalRandom.current().nextInt(5)+1;
            //随机性别
            int gender = ThreadLocalRandom.current().nextInt(2)+1;
            System.out.println("polar::"+polar+"  gender"+gender);
        }
    }

    public int getRoleId() {
        return SpringUtils.getIdentityService().getNextId(IdentityType.ROLE);
    }
    public static String getRandomString() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
